/*
 * Copyright (C) 2007 Jeffrey Palm.  All rights reserved.
 */

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

final class Post {

  private final String boundary = HTTP.GenerateBoundary();
  private String post = "";
  private final String url;

  public Post(String url) {this.url = url;}
  
  public String getURL() {return this.url;}
  
  public void addParam(String key, String val) {
    post +=
      "--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"" + key + "\"\r\n" +
      "\r\n" +
      val + "\r\n";
  }

  public void addFile(String key, File file, String type) {
    
    post += "--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\"\r\n" +
      "Content-Type: " + type + "\r\n" +
      "\r\n";
    post += toBytes(file);
    post += "\r\n";
  }

  public String send() throws Exception {
    String newPost = post + 
      "--" + boundary + "--\r\n";
    return HTTP.sendPostRequest(newPost,url,boundary);
  }

  static byte[] toBytes(File f) {
    if (f == null) return null;
    try {
      byte[] buf = new byte[(int)f.length()];
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
      for (int c=0; c<buf.length; c += in.read(buf,c,(int)(f.length()-c))) {}
      in.close();
      return buf;
    } catch (Exception e) {e.printStackTrace();}
    return null;
  }

}


/*
 * Copyright (C) 2006 Jeffrey Palm.  All rights reserved.
 */



/**
 * This work is licensed under a GNU General Public License 
 * (http://www.gnu.org/copyleft/gpl.html).
 * 
 * Title: 		Mobup
 * Version: 		0.3
 * Description:         Mobile uploader for Flickr
 * Creator:             Vincenzo Lembo and Matteo Penzo
 * Source:              http://mobup.org
 *
 */




/**
 * HTTP Class
 * 
 * This class allows to send GET and POST request to a web server
 *
 */

class HTTP {
    
	/*** Creates a new instance of HTTP */
	private HTTP() {}


	public static String sendPostRequest(String requeststring,String url,String boundary) throws Exception {
		return sendPostRequest(requeststring,url,boundary,"multipart/form-data");
	}
	/**
	 * send a POST request to Web server
	 */
	public static String sendPostRequest(String requeststring,String url,String boundary,String type) throws Exception {
		HttpURLConnection hc = null;
		DataInputStream dis = null;
		DataOutputStream dos = null;
		StringBuffer messagebuffer = new StringBuffer();
		try {
				// Open up an http connection with the Web server
				// for both send and receive operations
			//hc = (HttpURLConnection)Connector.open(url, Connector.READ_WRITE);
			hc = (HttpURLConnection)new URL(url).openConnection();
      hc.setDoOutput(true);
      // Set the request method to POST
      //hc.setRequestMethod(HttpConnection.POST);
      hc.setRequestMethod("POST");
      //add property for the multipart/form-data Content-Type
      hc.setRequestProperty("Content-Type", "" + type + "; boundary=" + boundary);
                
      // Send the string entered by user byte by byte
      //dos = hc.openDataOutputStream();
      dos = new DataOutputStream(hc.getOutputStream());
      byte[] request_body = requeststring.getBytes();
      for (int i = 0; i < request_body.length; i++) {
        dos.writeByte(request_body[i]);
      }
                
      dos.close();

      // Retrieve the response back from the servlet
      //messagebuffer.append(hc.getResponseMessage() + "\r\n");
      dis = new DataInputStream(hc.getInputStream());
      int ch;
      // Check the Content-Length first
      long len = hc.getContentLength(); 
      if(len!=-1) 
        {
          for(int i = 0;i<len;i++)
            {
              if((ch = dis.read())!= -1)
                {
                  messagebuffer.append((char)ch);
                }
            }
        } 
      else 
        {
          // if the content-length is not available
          while ((ch = dis.read()) != -1)
            messagebuffer.append((char) ch);
                    
        }
      dis.close();
 
    } catch (IOException ioe) {
			messagebuffer = new StringBuffer("ERROR!");
      ioe.printStackTrace();
                    
		} finally {
			// Free up i/o streams and http connection
			try { 
				if (hc != null) hc.disconnect();
			} catch (Exception ignored) {}
			try { 
				if (dis != null) dis.close();
			} catch (IOException ignored) {}
			try { 
				if (dos != null) dos.close();
			} catch (IOException ignored) {}
		}
		return messagebuffer.toString();
	}
    
	/**
	 * send a GET request to Web server
	 */
	public static String sendGetRequest(String url) {
		HttpURLConnection hc = null;
		DataInputStream dis = null;
		DataOutputStream dos = null;
		StringBuffer messagebuffer = new StringBuffer();
		try 
			{
				// Open up an http connection with the Web server
				// for both send and receive operations
				//hc = (HttpURLConnection)Connector.open(url, Connector.READ_WRITE);
				hc = (HttpURLConnection)new URL(url).openConnection();
				// Set the request method to POST
				//hc.setRequestMethod(HttpConnection.GET);
				hc.setRequestMethod("GET");
                
  
				// Retrieve the response back from the servlet
				messagebuffer.append(hc.getResponseMessage() + "\r\n");
				dis = new DataInputStream(hc.getInputStream());
				int ch;
				// Check the Content-Length first
				long len = hc.getContentLength(); 
				if(len!=-1) 
					{
						for(int i = 0;i<len;i++)
							{
								if((ch = dis.read())!= -1)
									{
										messagebuffer.append((char)ch);
									}
							}
					} 
				else 
					{
						// if the content-length is not available
						while ((ch = dis.read()) != -1)
							messagebuffer.append((char) ch);
					}
				dis.close();
 
			} catch (IOException ioe) {
			messagebuffer = new StringBuffer("ERROR!");
                    
		} finally {
			// Free up i/o streams and http connection
			try { 
				if (hc != null) hc.disconnect();
			} catch (Exception ignored) {}
			try { 
				if (dis != null) dis.close();
			} catch (IOException ignored) {}
			try { 
				if (dos != null) dos.close();
			} catch (IOException ignored) {}
		}
		return messagebuffer.toString();
	}

	public static String GenerateBoundary() {
		String boundary ="";
		Random random = new Random();
		Date date = new Date();
		random.setSeed(date.getTime());
		
		boundary += Integer.toHexString(random.nextInt());
		boundary += Integer.toHexString(random.nextInt());
		
		return "---------------------------" + boundary.substring(4);
	}
}
